<template>
  <div>
    <div class="operator-container">
      <el-button icon="el-icon-plus" type="primary" @click="addGroup(0,1)" class="operator-item" size="small">添加一级分类</el-button>
    </div>
    <el-table :data="formatData" :row-style="showRow" v-bind="$attrs">
      <el-table-column v-if="columns.length===0">
        <template slot-scope="scope">
          <span v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span>
          <span
            class="tree-ctrl"
            v-if="iconShow(0,scope.row)"
            @click="toggleExpanded(scope.$index)"
          >
            <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
            <i v-else class="el-icon-minus"></i>
          </span>
          {{scope.$index}}
        </template>
      </el-table-column>
      <el-table-column
        v-else
        v-for="(column, index) in columns"
        :key="column.value"
        :label="column.text"
      >
        <template slot-scope="scope">
          <span
            v-if="index === 0"
            v-for="space in scope.row._level"
            class="ms-tree-space"
            :key="space"
          ></span>
          <span
            class="tree-ctrl"
            v-if="iconShow(index,scope.row)"
            @click="toggleExpanded(scope.$index)"
          >
            <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
            <i v-else class="el-icon-minus"></i>
          </span>
          {{ categoryType == 1 ? `${scope.row.nameCn}/${scope.row.nameEn}` : `${scope.row.nameCn}` }}
        </template>
      </el-table-column>
      <el-table-column label="分组图片" align="center" width="150">
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="hover">
            <img :src="scope.row.cover" class="previewImage">
            <img v-popover:popover :src="scope.row.cover" class="thumbnail" slot="reference">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="移动" align="center" width="200">
        <template slot-scope="scope">
          <el-button plain size="mini" @click="move(scope.row.id, 1)" type="success">上移</el-button>
          <el-button plain size="mini" @click="move(scope.row.id, 2)" type="success">下移</el-button>
        </template>
      </el-table-column>
      <slot></slot>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row._level == 1"
            plain
            size="mini"
            @click="addGroup(scope.row.id,2)"
            type="primary"
          >添加二级分类</el-button>
          <el-button
            v-else-if="scope.row._level == 2 && isHaveThree"
            plain
            size="mini"
            @click="addGroup(scope.row.id,3)"
            type="success"
          >添加三级分类</el-button>
          <el-button
            plain
            size="mini"
            type="primary"
            @click="updateCategory(scope.row)"
          >编辑</el-button>
          <el-button plain size="mini" type="danger" @click="delCategory(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="720px">
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogRules" label-position="right" label-width="140px">
        <el-form-item prop="nameCn" label="中文分类名称：">
          <el-input placeholder="请输入中文分类名称最多10个字" size="small" v-model="dialogForm.nameCn"></el-input>
        </el-form-item>
        <el-form-item prop="nameEn" label="英文分类名称：" v-if="categoryType == 1">
          <el-input placeholder="请输入英文分类名称最多20个字符" size="small" v-model="dialogForm.nameEn"></el-input>
        </el-form-item>
        <el-form-item prop="cover" label="分类图片：">
          <span>建议尺寸800*800像素以上，大小2M以下；支持jpg、jpeg、png；只能上传一张图片</span>
          <el-upload
            :headers="headers"
            class="avatar-uploader"
            :multiple="false"
            :action="importFileUrl"
            list-type="picture-card"
            :name="uploadFileName"
            :limit="1"
            :file-list="pictureList"
            :onError="uploadError"
            :onSuccess="uploadSuccess"
            :on-remove="uploadRemove"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类描述（非必填）：" v-if="dialogForm.level === 1">
          <el-input
            placeholder="请输入分类描述最多50个字符"
            size="small"
            v-model="dialogForm.categoryDesc"
            maxlength:50
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="editDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveGroup">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="delDioalog" width="45%">
      <p>将永久删除此分类，确定删除？</p>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="delDioalog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="sureDelgroup">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import treeToArray from './eval'
import { Message } from 'element-ui'
export default {
  name: 'treeTable',
  props: {
    data: {
      type: [Array, Object],
      required: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    evalFunc: Function,
    evalArgs: Array,
    expandAll: {
      type: Boolean,
      default: false
    },
    isHaveThree: {
      type: Boolean,
      default: true
    },
    categoryType: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      dialogTitle: '添加分类',
      editDialogVisible: false, // 编辑框
      delDioalog: false, // 确认删除框
      dialogForm: {
        fid: 0,
        id: 0,
        nameCn: '',
        nameEn: '',
        cover: '',
        categoryDesc: '',
        categoryType: 0, // 1前台，2后台
        level: 1
      },
      dialogRules: {
        nameCn: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('不能为空'))
            } else if (value.length > 10) {
              callback(new Error('中文商品名称最多10个字'))
            } else {
              callback()
            }
          }
        },
        nameEn: {
          required: this.categoryType === 1,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('不能为空'))
            } else if (value.length > 20) {
              callback(new Error('英文商品名称最多20个字符'))
            } else {
              callback()
            }
          }
        },
        cover: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请上传一张图片'))
            } else {
              callback()
            }
          }
        },
        categoryDesc: {
          required: false,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value.length > 50) {
              callback(new Error('分类描述最多50个字符'))
            } else {
              callback()
            }
          }
        }
      },
      pictureList: [],
      importFileUrl: `${process.env.VUE_APP_UPLOAD_API}`,
      uploadFileName: `${process.env.VUE_APP_UPLOAD_NAME}`,
      headers: this.$headers,
      currPage: 20,
      con: 0,
      delgroupId: ''
    }
  },
  computed: {
    // 格式化数据源
    formatData: function () {
      let tmp
      if (!Array.isArray(this.data)) {
        tmp = [this.data]
      } else {
        tmp = this.data
      }
      const func = this.evalFunc || treeToArray
      const args = this.evalArgs
        ? Array.concat([tmp, this.expandAll], this.evalArgs)
        : [tmp, this.expandAll]

      return func.apply(null, args)
    }
  },
  mounted () {
  },
  methods: {
    sureDelgroup () {
      this.$emit('deleteCategory', this.delgroupId)
      this.delDioalog = false
    },
    showRow (row) {
      const show = row.row.parent
        ? row.row.parent._expanded && row.row.parent._show
        : true
      row.row._show = show
      return show
        ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;'
        : 'display:none;'
    },
    move (id, status) {
      // 1上移，2下移
      this.$emit('move', id, status)
    },
    toggleExpanded (trIndex) {
      const record = this.formatData[trIndex]
      record._expanded = !record._expanded
    },
    // 删除分类
    delCategory (categoryId) {
      this.delgroupId = categoryId
      this.delDioalog = true
    },
    // 上传成功后的回调
    uploadSuccess (response, file, fileList) {
      this.dialogForm.cover = response.data
      this.pictureList.push({
        url: response.data
      })
    },
    // 上传错误
    uploadError (response, file, fileList) {
      Message('上传失败，请重试！')
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload (file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isIMAGE) {
        Message('上传模板只能是 jpg/png 格式!')
      }
      if (!isLt2M) {
        Message('上传模板大小不能超过 2MB!')
      }
      return isIMAGE && isLt2M
    },
    // 删除图片
    uploadRemove (file, fileList) {
      this.dialogForm.cover = ''
      Message('删除图片成功!')
      this.pictureList = []
    },
    // 添加分类
    addGroup (fid, level) {
      if (level === 1) {
        this.dialogTitle = '添加一级分类'
      } else if (level === 2) {
        this.dialogTitle = '添加二级分类'
      } else if (level === 3) {
        this.dialogTitle = '添加三级分类'
      }
      this.dialogForm.level = level
      this.dialogForm.fid = fid
      this.dialogForm.id = ''
      this.dialogForm.cover = '' // 分类图片
      this.dialogForm.categoryDesc = '' // 分类描述
      this.dialogForm.nameCn = ''
      this.dialogForm.nameEn = ''
      this.dialogForm.categoryType = this.categoryType
      this.pictureList = []
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate()
      })
      this.editDialogVisible = true
    },
    // 修改分类
    updateCategory ({ id, fid, cover, nameCn, nameEn, categoryDesc, _level }) {
      if (_level === 1) {
        this.dialogTitle = '编辑一级分类'
      } else if (_level === 2) {
        this.dialogTitle = '编辑二级分类'
      } else if (_level === 3) {
        this.dialogTitle = '编辑三级分类'
      }
      this.dialogForm.categoryType = this.categoryType
      this.dialogForm.nameCn = nameCn
      this.dialogForm.nameEn = nameEn
      this.dialogForm.fid = fid
      this.dialogForm.id = id
      this.dialogForm.categoryDesc = categoryDesc
      this.dialogForm.level = _level
      this.dialogForm.cover = cover
      this.pictureList = []
      this.pictureList.push({
        url: cover
      })
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate()
      })
      this.editDialogVisible = true
    },
    // 保存分类信息
    saveGroup () {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          // this.dialogForm.cover = this.pictureList[0].url
          this.$emit('editCategory', this.dialogForm)
          this.editDialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 图标显示
    iconShow (index, record) {
      return index === 0 && record.subdivision && record.subdivision.length > 0
    }
  }
}
</script>
<style rel="stylesheet/css">
@keyframes treeTableShow {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@-webkit-keyframes treeTableShow {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
$color-blue: #2196f3;
$space-width: 18px;
.ms-tree-space {
  position: relative;
  top: 1px;
  display: inline-block;
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  width: $space-width;
  height: 14px;
  &::before {
    content: "";
  }
}
.processContainer {
  width: 100%;
  height: 100%;
}
table td {
  line-height: 26px;
}
.tree-ctrl {
  position: relative;
  cursor: pointer;
  color: $color-blue;
  margin-left: -$space-width;
}
.img-wrap {
  width: 70px;
}
.img-wrap img {
  width: 100%;
}
.botton-wrap {
  margin: 10px 0px 10px 40px;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
